package com.ncmmall.application.business.order;

import cn.hutool.core.date.DateUtil;
import com.ncmmall.application.business.order.wechat.WechatRefundRequest;
import com.ncmmall.application.msm.AliYunSmsService;
import com.ncmmall.application.util.AlipayUtil;
import com.ncmmall.application.util.WechatPayUtil;
import com.feijin.commons.domain.Ids;
import com.feijin.commons.lang.ArithUtils;
import com.feijin.commons.lang.PropertiesHelps;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.distribution.DistributionOrder;
import com.ncmmall.domain.business.distribution.DistributionOrderRepository;
import com.ncmmall.domain.business.distribution.QDistributionOrder;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.GoodsRepository;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.sku.GoodsSku;
import com.ncmmall.domain.business.goods.sku.GoodsSkuRepository;
import com.ncmmall.domain.business.goods.sku.QGoodsSku;
import com.ncmmall.domain.business.live.LiveOrder;
import com.ncmmall.domain.business.live.LiveOrderRepository;
import com.ncmmall.domain.business.live.QLiveOrder;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecord;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecordRepository;
import com.ncmmall.domain.business.message.Message;
import com.ncmmall.domain.business.message.MessageRepository;
import com.ncmmall.domain.business.order.Order;
import com.ncmmall.domain.business.order.OrderDetail;
import com.ncmmall.domain.business.order.OrderDetailRepository;
import com.ncmmall.domain.business.order.OrderRepository;
import com.ncmmall.domain.business.order.QOrder;
import com.ncmmall.domain.business.order.QOrderDetail;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSale;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleCheckRecord;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleCheckRecordRepository;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleDetail;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleDetailRepository;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleImage;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleImageRepository;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleRepository;
import com.ncmmall.domain.business.order.aftersale.QOrderAfterSale;
import com.ncmmall.domain.business.order.dto.OrderDTO;
import com.ncmmall.domain.business.order.lading.BillOfLading;
import com.ncmmall.domain.business.order.lading.QBillOfLading;
import com.ncmmall.domain.business.trading.TradingLog;
import com.ncmmall.domain.business.trading.TradingLogRepository;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 售后订单模块
 *
 * @author linxs
 * @date 2019-07-23 14:13
 */
@Service
@Transactional
public class OrderAfterSaleApplication {

    @Autowired
    private OrderAfterSaleImageRepository orderAfterSaleImageRepository;

    @Autowired
    private OrderAfterSaleRepository orderAfterSaleRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderAfterSaleCheckRecordRepository checkRecordRepository;

    @Autowired
    private WebUserRepository memberRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private ShoppingCardRecordRepository shoppingCardRecordRepository;

    @Autowired
    private GoodsSkuRepository skuRepository;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private OrderAfterSaleDetailRepository afterSaleDetailRepository;

    @Autowired
    private TradingLogRepository tradingLogRepository;

    @Autowired
    private DistributionOrderRepository distributionOrderRepository;

    @Autowired
    private LiveOrderRepository liveOrderRepository;

    /**
     * 申请订单售后
     */
    public OrderAfterSale apply(OrderAfterSale params) {

        OrderDetail orderDetail = queryChannelService.findOne(QOrderDetail.orderDetail.id.eq(params.getOrderDetails().get(0).getId()), OrderDetail.class);
        Requires.isTrue(orderDetail.getOrder().getApplyDistributor() == null, "申请成为分销商订单无法售后");

        Order order = queryChannelService.findOne(QOrder.order.id.eq(orderDetail.getOrder().getId()), Order.class);

        OrderAfterSale afterSale = new OrderAfterSale();
        afterSale.setMember(params.getMember());
        afterSale.setCreateTime(new Timestamp(System.currentTimeMillis()));
        afterSale.setAfterSaleReason(params.getAfterSaleReason());
        afterSale.setNote(params.getNote());
        afterSale.setOrder(order);

        if (order.getIsIssuingType() == 1) {
            afterSale.setMerchant(order.getSupplier());
        } else {
            afterSale.setMerchant(order.getMerchant());
        }

        afterSale.setStatus(1);
        afterSale.setCheckStatus(1);
        afterSale.setApplyOfOrderStatus(order.getStatus());
        orderAfterSaleRepository.save(afterSale);

        for (OrderDTO dto : params.getOrderDetails()) {
            OrderDetail detail = queryChannelService.findOne(QOrderDetail.orderDetail.id.eq(dto.getId()), OrderDetail.class);
            OrderAfterSaleDetail item = new OrderAfterSaleDetail();
            item.setOrderDetail(detail);
            item.setAfterSaleOrder(afterSale);
            afterSaleDetailRepository.save(item);

            detail.setIsAfterSale(1);
            orderDetailRepository.save(detail);
        }
        afterSale.setRefundPrice(order.getMoney());
        orderAfterSaleRepository.save(afterSale);

        for (OrderAfterSaleImage item : params.getImages()) {
            OrderAfterSaleImage image = new OrderAfterSaleImage();
            image.setMerchant(order.getMerchant());
            image.setName(item.getName());
            image.setCreateTime(new Timestamp(System.currentTimeMillis()));
            image.setOrderAfterSale(afterSale);
            image.setMember(afterSale.getMember());
            orderAfterSaleImageRepository.save(image);
        }


        order = queryChannelService.findOne(QOrder.order.eq(order), Order.class);
        order.setIsAfterSale(1);
        orderRepository.save(order);

        OrderAfterSaleCheckRecord checkRecord = new OrderAfterSaleCheckRecord();
        checkRecord.setAfterSale(afterSale);
        checkRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        checkRecord.setContent("您的服务单已申请成功，待售后审核中");
        checkRecordRepository.save(checkRecord);

        //如果订单是分销订单，取消分销, 如果售后失败，需要改回待发放状态
        List<DistributionOrder> distributionOrders = queryChannelService.findAll(QDistributionOrder.distributionOrder.order.id.eq(order.getId()).and(QDistributionOrder.distributionOrder.distrtionPay.eq(1)), DistributionOrder.class);
        for (DistributionOrder item : distributionOrders) {
            item.setDistrtionPay(3);
        }
        distributionOrderRepository.save(distributionOrders);

        //如果订单是直播分销订单，取消分销，如果售后失败，需要改回待发放状态
        List<LiveOrder> liveOrders = queryChannelService.findAll(QLiveOrder.liveOrder.order.eq(order).and(QLiveOrder.liveOrder.sendStatus.eq(1)), LiveOrder.class);
        for (LiveOrder item : liveOrders) {
            item.setSendStatus(3);
        }
        liveOrderRepository.save(liveOrders);

        try {
            AliYunSmsService.send(order.getMerchant().getMobile(),
                    PropertiesHelps.getValue("sign_name"),
                    "SMS_210995744",
                    ImmutableMap.of("orderNo", order.getOrderNo(), "refundAmount", String.valueOf(order.getPrice())));
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return afterSale;

    }

    /**
     * 审核
     */
    public void check(OrderAfterSale params) {

        OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(params.getId()), OrderAfterSale.class);
        afterSale.setCheckStatus(params.getCheckStatus());
        afterSale.setConsignee(params.getConsignee());
        afterSale.setConsigneeMobile(params.getConsigneeMobile());
        afterSale.setConsigneeAddress(params.getConsigneeAddress());


        Message message = new Message();
        message.setType(2);
        message.setMember(afterSale.getMember());
        message.setOrderAfterSaleId(afterSale.getId());
        message.setDigest("退款订单号:" + afterSale.getOrder().getOrderNo());
        message.setCreateTime(new Timestamp(System.currentTimeMillis()));

        if (params.getCheckStatus() == 2) {
            OrderAfterSaleCheckRecord checkRecord = new OrderAfterSaleCheckRecord();
            checkRecord.setAfterSale(afterSale);
            checkRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
            checkRecord.setContent("您的服务单已审核通过，请将订单内的商品寄回");
            checkRecordRepository.save(checkRecord);

            message.setTitle("您有1笔退款申请已通过，请按商家提供的退货地址退回商品");
        }

        if (params.getCheckStatus() == 3) {
            OrderAfterSaleCheckRecord checkRecord = new OrderAfterSaleCheckRecord();
            checkRecord.setAfterSale(afterSale);
            checkRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
            checkRecord.setContent("您的服务单审核不通过");
            checkRecordRepository.save(checkRecord);

            afterSale.setStatus(3);
            afterSale.setReason(params.getReason());

            message.setTitle("您有1笔退款申请已驳回");

            //审核驳回，如果是分销订单，改回待发放
            List<DistributionOrder> distributionOrders = queryChannelService.findAll(QDistributionOrder.distributionOrder.order.id.eq(afterSale.getOrder().getId()).and(QDistributionOrder.distributionOrder.distrtionPay.eq(3)), DistributionOrder.class);
            for (DistributionOrder item : distributionOrders) {
                item.setDistrtionPay(1);
            }
            distributionOrderRepository.save(distributionOrders);

            List<LiveOrder> liveOrders = queryChannelService.findAll(QLiveOrder.liveOrder.order.eq(afterSale.getOrder()).and(QLiveOrder.liveOrder.sendStatus.eq(3)), LiveOrder.class);
            for (LiveOrder item : liveOrders) {
                item.setSendStatus(1);
            }
            liveOrderRepository.save(liveOrders);
        }

        messageRepository.save(message);
        orderAfterSaleRepository.save(afterSale);
    }

    /**
     * 寄回
     */
    public void sendBack(long id, String expressCompany, String expressNo) {
        OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(id), OrderAfterSale.class);
        afterSale.setExpressCompany(expressCompany);
        afterSale.setExpressNo(expressNo);
        afterSale.setCheckStatus(4);
        orderAfterSaleRepository.save(afterSale);

        OrderAfterSaleCheckRecord checkRecord = new OrderAfterSaleCheckRecord();
        checkRecord.setAfterSale(afterSale);
        checkRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        checkRecord.setContent("买家已寄回相关物品");
        checkRecordRepository.save(checkRecord);

    }

    /**
     * 商家签收
     */
    public void signFor(OrderAfterSale params) {
        OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(params.getId()), OrderAfterSale.class);
        afterSale.setCheckStatus(5);
        orderAfterSaleRepository.save(afterSale);

        OrderAfterSaleCheckRecord checkRecord = new OrderAfterSaleCheckRecord();
        checkRecord.setAfterSale(afterSale);
        checkRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        checkRecord.setContent("商家已签收");
        checkRecordRepository.save(checkRecord);

    }

    /**
     * 采购订单售后退款
     */
    public void refundOfPuracherOrder(OrderAfterSale params) {
        OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(params.getId()), OrderAfterSale.class);
        afterSale.setCheckStatus(6);
        afterSale.setStatus(2);
        afterSale.setRefundTime(new Timestamp(System.currentTimeMillis()));
        orderAfterSaleRepository.save(afterSale);

        Order order = queryChannelService.findOne(QOrder.order.id.eq(afterSale.getOrder().getId()), Order.class);
        order.setStatus(5);//订单完成

        orderRepository.save(order);

        if (ArithUtils.sub(order.getPrice(), afterSale.getRefundPrice()) > 0) {

            double price = ArithUtils.sub(order.getPrice(), afterSale.getRefundPrice());
            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.eq(order.getMerchant()), WebUser.class);
            if (order.getPayMethod() != 5) {//非线下转账的订单

                //商家订单金额到账
                merchant.setBalance(ArithUtils.add(merchant.getBalance(), price));
                merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), price));
                merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
                memberRepository.save(merchant);

                //商户订单金额到账流水记录
                TradingLog tradingLog = new TradingLog();
                tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
                tradingLog.setMerchant(merchant);
                tradingLog.setStatus(1);
                tradingLog.setType(1);
                tradingLog.setAmount(price);
                tradingLog.setOrderNo(order.getOrderNo());
                tradingLogRepository.save(tradingLog);
            } else {

                //商家订单金额到账
                merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), price));
                merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
                memberRepository.save(merchant);
            }
        }


        if (order.getPayMethod() != 5) {

            WebUser member = queryChannelService.findOne(QWebUser.webUser.id.eq(order.getMember().getId()), WebUser.class);
            member.setBalance(ArithUtils.add(member.getBalance(), afterSale.getRefundPrice()));
            memberRepository.save(member);

            TradingLog tradingLog = new TradingLog();
            tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
            tradingLog.setMerchant(member);
            tradingLog.setStatus(1);
            tradingLog.setType(5);
            tradingLog.setAmount(afterSale.getRefundPrice());
            tradingLog.setOrderNo(order.getOrderNo());
            tradingLogRepository.save(tradingLog);

        }

        OrderAfterSaleCheckRecord checkRecord = new OrderAfterSaleCheckRecord();
        checkRecord.setAfterSale(afterSale);
        checkRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        checkRecord.setContent("您的订单款项已退回");
        checkRecordRepository.save(checkRecord);

        //加库存，减销量
        List<OrderAfterSaleDetail> details = afterSale.getDetails();

        for (OrderAfterSaleDetail item : details) {
            OrderDetail detail = item.getOrderDetail();
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);
            sku.setStore((sku.getStore() + detail.getQuantity()));
            skuRepository.save(sku);

            Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);
            goods.setStore((goods.getStore() + detail.getQuantity()));
            goods.setSalesVolume(Math.max(goods.getSalesVolume() - detail.getQuantity(), 0));

            if (goods.getStatus() == 6) {
                goods.setStatus(3);
            }

            goodsRepository.save(goods);
        }
    }

    /**
     * 退款
     */
    public void refund(OrderAfterSale params) {

        OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(params.getId()), OrderAfterSale.class);
        afterSale.setCheckStatus(6);
        afterSale.setStatus(2);
        afterSale.setRefundTime(new Timestamp(System.currentTimeMillis()));
        afterSale.setOutRefundNo(Ids.generateId());
        orderAfterSaleRepository.save(afterSale);

        //微信支付
        if (afterSale.getOrder().getPayMethod() == 1) {

            Map<String, String> refundResult;
            if (afterSale.getOrder().getAppPay() == 1) {
                refundResult = WechatPayUtil.refund(afterSale.getOrder().getPayNo(), afterSale.getOutRefundNo(), afterSale.getOrder().getMoney(), afterSale.getRefundPrice());
            } else {
                refundResult = new WechatRefundRequest(afterSale.getOrder().getPayNo(), afterSale.getOrder().getMoney(), afterSale.getRefundPrice(), afterSale.getOutRefundNo()).refundByWechatMp();
            }

            if (refundResult.get("flag").equals("true")) {
                String refundId = refundResult.get("no");

                afterSale.setWechatRefundId(refundId);
                orderAfterSaleRepository.save(afterSale);

                OrderAfterSaleCheckRecord checkRecord = new OrderAfterSaleCheckRecord();
                checkRecord.setAfterSale(afterSale);
                checkRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
                checkRecord.setContent("您的订单款项已按您原支付渠道退回至您的微信钱包余额");
                checkRecordRepository.save(checkRecord);


                //赠品活动订单，给赠品加库存
                if (afterSale.getOrder().getMarketingType() == 1) {

                    List<Goods> giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", afterSale.getOrder().getGiftActivity().getId()), Goods.class);

                    for (Goods giftGoodse : giftGoodses) {
                        giftGoodse.setStore(giftGoodse.getStore() + 1);
                        giftGoodse.setSalesVolume(giftGoodse.getSalesVolume() - 1);
                        goodsRepository.save(giftGoodse);

                        GoodsSku sku = giftGoodse.getSkus().get(0);
                        sku.setStore(sku.getStore() + 1);
                        skuRepository.save(sku);
                    }
                }
            } else {
                throw new IllegalArgumentException("[微信退款失败] " + refundResult.get("message"));
            }
        }

        //支付宝支付
        if (afterSale.getOrder().getPayMethod() == 2 && afterSale.getOrder().getAppPay() == 1) {
            try {
                AlipayUtil.refund(afterSale.getOrder().getPayNo(), afterSale.getOrder().getMoney());
            } catch (Exception e) {
                throw new IllegalArgumentException("[支付宝退款失败]" + e.getMessage());
            }
        }

        //赠品活动订单，给赠品减库存
        if (afterSale.getOrder().getMarketingType() == 1) {
            List<Goods> giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", afterSale.getOrder().getGiftActivity().getId()), Goods.class);
            for (Goods giftGoodse : giftGoodses) {
                giftGoodse.setStore(giftGoodse.getStore() + 1);
                giftGoodse.setSalesVolume(giftGoodse.getSalesVolume() - 1);
                goodsRepository.save(giftGoodse);

                GoodsSku sku = giftGoodse.getSkus().get(0);
                sku.setStore(sku.getStore() + 1);
                skuRepository.save(sku);
            }
        }

        Order order = queryChannelService.findOne(QOrder.order.id.eq(afterSale.getOrder().getId()), Order.class);
        order.setStatus(5);
        orderRepository.save(order);

        //结算 的时候要减掉已售后的钱
        //商家订单金额到账

        if (ArithUtils.sub(order.getPrice(), afterSale.getRefundPrice()) > 0) {

            double price = ArithUtils.sub(order.getPrice(), afterSale.getRefundPrice());

            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.eq(order.getMerchant()), WebUser.class);
            merchant.setBalance(ArithUtils.add(merchant.getBalance(), price));
            merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), price));
            merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
            memberRepository.save(merchant);

            //商户订单金额到账流水记录
            TradingLog tradingLog = new TradingLog();
            tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
            tradingLog.setMerchant(merchant);
            tradingLog.setStatus(1);
            tradingLog.setType(1);
            tradingLog.setAmount(price);
            tradingLog.setOrderNo(order.getOrderNo());
            tradingLogRepository.save(tradingLog);


            if (order.getIsCloudStoreDelivery() == 1) {

                List<BillOfLading> billOfLadings = queryChannelService.findAll(QBillOfLading.billOfLading.order.eq(order).and(QBillOfLading.billOfLading.status.eq(4)), BillOfLading.class);
                for (BillOfLading billOfLading : billOfLadings) {
                    WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(billOfLading.getSupplier().getId()), WebUser.class);
                    supplier.setBalance(ArithUtils.add(supplier.getBalance(), billOfLading.getPrice()));
                    memberRepository.save(supplier);

                    TradingLog tradingLog2 = new TradingLog();
                    tradingLog2.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    tradingLog2.setMerchant(supplier);
                    tradingLog2.setStatus(1);
                    tradingLog2.setType(6);
                    tradingLog2.setAmount(billOfLading.getPrice());
                    tradingLog2.setOrderNo(billOfLading.getOrderNo());
                    tradingLogRepository.save(tradingLog2);
                }

            }


        }


        //加库存，减销量
        List<OrderAfterSaleDetail> details = afterSale.getDetails();

        for (OrderAfterSaleDetail item : details) {

            OrderDetail detail = item.getOrderDetail();
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);
            sku.setStore((sku.getStore() + detail.getQuantity()));

            //拼团活动订单
            if (detail.getMarketingType() == 2) {
                sku.setGroupBookingStore(sku.getGroupBookingStore() + detail.getQuantity());
            }

            //特价活动商品
            if (detail.getMarketingType() == 3) {
                sku.setBargainStore(sku.getBargainStore() + detail.getQuantity());
            }

            //秒杀活动商品
            if (detail.getMarketingType() == 4) {
                sku.setSeckillStore(sku.getSeckillStore() + detail.getQuantity());
            }

            skuRepository.save(sku);

            Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);
            goods.setStore((goods.getStore() + detail.getQuantity()));
            goods.setSalesVolume(Math.max(goods.getSalesVolume() - detail.getQuantity(), 0));

            //拼团活动订单
            if (detail.getMarketingType() == 2) {
                goods.setGroupBookingStore(goods.getGroupBookingStore() + detail.getQuantity());
                goods.setGroupBookingSalesVolume(goods.getGroupBookingSalesVolume() - detail.getQuantity());


                if (goods.getGroupBookingStatus() == 6 && DateUtil.parse(goods.getGroupBookingEndTime(), "yyyy-MM-dd HH:mm").getTime() >= new Date().getTime()) {
                    goods.setGroupBookingStatus(5);
                }
            }

            //特价活动商品
            if (detail.getMarketingType() == 3) {
                goods.setBargainStore(goods.getBargainStatus() + detail.getQuantity());
                goods.setBargainSalesVolume(goods.getBargainSalesVolume() - detail.getQuantity());
                if (goods.getBargainStatus() == 6 && DateUtil.parse(goods.getEndDateOfValidity(), "yyyy-MM-dd HH:mm").getTime() >= new Date().getTime()) {
                    goods.setBargainStatus(5);
                }
            }

            //秒杀活动商品
            if (detail.getMarketingType() == 4) {
                goods.setSeckillStore(goods.getSeckillStore() + detail.getQuantity());
                goods.setSeckillSalesVolume(goods.getSeckillSalesVolume() - detail.getQuantity());
                if (goods.getSeckillStatus() == 6 && DateUtil.parse(goods.getSeckillSession().getSeckillTime() + " " + goods.getSeckillSession().getSeckillEndTime(), "yyyy-MM-dd HH:mm").getTime() >= new Date().getTime()) {
                    goods.setSeckillStatus(5);
                }
            }

            //预售活动商品
            if (detail.getMarketingType() == 5) {
                goods.setPresellSalesVolume(goods.getPresellSalesVolume() - detail.getQuantity());
            }

            if (goods.getStatus() == 6) {
                goods.setStatus(3);
            }

            goodsRepository.save(goods);
        }

        // 订单购物卡余额退还
        if (order.getHavaShoppingCardRecord() == 1) {
            ShoppingCardRecord record = order.getShoppingCardRecord();
            if (record.getStatus() != 3) {
                record.setStatus(1);
                record.setBalance(ArithUtils.roundHalfUp(ArithUtils.add(record.getBalance(), order.getShoppingCardMoney()), 2));
                shoppingCardRecordRepository.save(record);
            }
        }
    }
}
